package com.zcl.Thread.t9;

import java.util.concurrent.locks.ReentrantLock;

/**
 * @Description:
 * @author: zcl
 * @date: 2022/3/10  16:16
 * <p>
 * 解决线程安全问题的方式三: Lock锁   ---JDK 5.0 新增
 */


class Window implements Runnable {
    private static int ticket = 100;

    private ReentrantLock lock = new ReentrantLock();

    @Override
    public void run() {
        while (true) {
            lock.lock();
            try {
                Thread.sleep(100);
                if (ticket > 0) {
                    System.out.println(Thread.currentThread().getName() + ": 售票, 票号为: " + ticket);
                    ticket--;
                } else {
                    break;
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                lock.unlock();
            }
        }
    }
}

public class LockTest {
    public static void main(String[] args) {
        Window w = new Window();
        Thread t1 = new Thread(w);
        Thread t2 = new Thread(w);
        Thread t3 = new Thread(w);
        t1.setName("窗口1");
        t2.setName("窗口2");
        t3.setName("窗口3");
        t1.start();
        t2.start();
        t3.start();
    }

}
